package com.ccys.common.third.aws.polly;


import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.polly.AmazonPolly;
import com.amazonaws.services.polly.AmazonPollyClient;
import com.amazonaws.services.polly.model.*;
import com.ccys.common.third.aws.s3.S3Constants;

import com.ccys.common.third.aws.s3.S3Util;
import com.ccys.common.util.StringUtil;

import javazoom.jl.player.advanced.AdvancedPlayer;
import javazoom.jl.player.advanced.PlaybackEvent;
import javazoom.jl.player.advanced.PlaybackListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import software.amazon.awssdk.regions.Region;




import java.io.*;



/**
 * 亚马逊 Amazon Polly
 * <p>
 * 参考在线文档：https://docs.aws.amazon.com/zh_cn/polly/latest/dg/what-is.html
 *
 * */
@Slf4j
@Component
@DependsOn({"s3Constants"})
public class PollyUtil {

    public static AmazonPolly client;

    public static String accessKey = "AKIAIHBBQGPKQR7KO5BQ";
    public static String secretKey = "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";


    //初始化SDK
    static {
        // 替换为你的S3桶所在的地区 "ap-southeast-1"
        System.setProperty("aws.region", Regions.AP_SOUTHEAST_1.getName());
        if(StringUtil.isNotEmpty(PollyConstants.region)) {
            if(Regions.US_WEST_1.getName().equals(PollyConstants.region)) {
                System.setProperty("aws.region", Region.US_WEST_1.toString());
            }
        }
        if(StringUtil.isNotEmpty(S3Constants.accessKeyId)) {
            PollyUtil.accessKey = S3Constants.accessKeyId;
        }
        if(StringUtil.isNotEmpty(S3Constants.accessKeySecret)) {
            PollyUtil.secretKey = S3Constants.accessKeySecret;
        }
        System.setProperty("aws.accessKeyId", PollyUtil.accessKey);
        System.setProperty("aws.secretAccessKey", PollyUtil.secretKey);
        client = AmazonPollyClient.builder()
            // 根据你的区域设置
            .withRegion(Regions.AP_SOUTHEAST_1)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(PollyUtil.accessKey, PollyUtil.secretKey)))
            .build();


    }

    private static final String SAMPLE = "Congratulations. You have successfully built this working demo of Amazon Polly in Java. Have fun building voice enabled apps with Amazon Polly (that's me!), and always look at the AWS website for tips and tricks on using Amazon Polly and other great services from AWS";


       /**
        * @description 文本合成音频文件
        * @date     2024/2/22
        * @author   cloud fly
        */
    public static void synthesizeToLocal(String text,String key) {
        SynthesizeSpeechRequest request = new SynthesizeSpeechRequest()
            .withText(text)
            .withVoiceId(VoiceId.Salli)
            .withOutputFormat(OutputFormat.Mp3);

        SynthesizeSpeechResult result = client.synthesizeSpeech(request);

        // 处理语音数据，保存到文件或者播放
        //InputStream audioStream = result.getAudioStream();
        try (InputStream audioStream = result.getAudioStream();
             //保存到文件
            FileOutputStream fileOutputStream = new FileOutputStream(key)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = audioStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("File saved successfully.");
            fileOutputStream.close();
            //create an MP3 player
            AdvancedPlayer player = new AdvancedPlayer(audioStream,
                javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice());

            player.setPlayBackListener(new PlaybackListener() {
                @Override
                public void playbackStarted(PlaybackEvent evt) {
                    System.out.println("Playback started");
                    System.out.println(SAMPLE);
                }

                @Override
                public void playbackFinished(PlaybackEvent evt) {
                    System.out.println("Playback finished");
                }
            });


            // play it!
            player.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

       /**
        * @description 文本合成语音，并且上传到S3 的铃声目录下
        * @param text 文本内容
        * @param bucketName 存储桶 有默认值可不传
        * @param key  文件名称 用户的userId
        * @return 播放地址
        * @date     2024/2/23
        * @author   cloud fly
        */
    public static String synthesizeToS3Ringtone(String text,String bucketName,String key) {
        if(StringUtil.isEmpty(bucketName)) {
            bucketName = S3Util.bucketName;
        }
        //规则  key  就是 userId
        String fileName = "Ringtone/" + key + ".mp3";
        SynthesizeSpeechRequest request = new SynthesizeSpeechRequest()
            .withText(text)
            .withVoiceId(VoiceId.Salli)
            .withOutputFormat(OutputFormat.Mp3);

        SynthesizeSpeechResult result = client.synthesizeSpeech(request);
        // 处理语音数据，保存到S3服务器
        //InputStream audioStream = result.getAudioStream();
        try (InputStream audioStream = result.getAudioStream();
            ) {
            S3Util.putS3ObjectByInputStream(bucketName, fileName, audioStream);
            System.out.println("File saved S3 successfully.");

        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = S3Util.getURL(S3Util.bucketName, fileName);
        return url;
    }

    public static void main(String args[]) throws Exception {

        PollyUtil.synthesizeToS3Ringtone("Hello word, Hello word,Hello word,Hello word,",S3Util.bucketName,"userIdOutput");
    }



}
